package com.qdu.config;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class SuccessHandler implements AuthenticationSuccessHandler{

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
		HttpSession session = request.getSession();
        String path = request.getContextPath() ;
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String uid = (String)request.getAttribute("username");
        System.out.println("id"+authentication.getName());
        if (roles.contains("ROLE_user")){
        	
        	session.setAttribute("islogin", true);
        	session.setAttribute("id", authentication.getName());
            response.sendRedirect(basePath+"user/d?uid="+authentication.getName());
            return;
        }
        if (roles.contains("ROLE_admin")){
        	session.setAttribute("islogin", true);
        	session.setAttribute("id", authentication.getName());
            response.sendRedirect(basePath+"admin");
            return;
        }
        if (roles.contains("ROLE_hr")){
        	session.setAttribute("islogin", true);
        	session.setAttribute("id", authentication.getName());
        	response.sendRedirect(basePath+"hr/d?hid="+authentication.getName());
 
            return;
        }
        response.sendRedirect(basePath+"home");
		
	}

}
